#coding:UTF-8
__author__ = 'huxiaoliang'

import re
import pickle as p

ab = {}
modifyFlag=False


def add():
    global modifyFlag
    name = input('输入姓名')
    if name not in ab:
        ab[name]={}
        phoneNumber = input('输入正确电话号码')
        while(not phoneCheck(phoneNumber)):
             phoneNumber = input('输入电话号码')
        ab[name]['phone']= phoneNumber
        wechatNumber = input('输入微信号码')
        ab[name]['wechat'] =wechatNumber
        modifyFlag=True
        input('添加成功，按回车键继续')
    else:
        print(name + '已存在')
        input('输入回车键继续')

def delete():
    global modifyFlag
    name = input('输入姓名')
    if name in ab:
        confirm=input("确认删除全部联系人请输入:YES")
        if (confirm=='YES'):
            del ab[name]
            modifyFlag=True
            print('删除成功')
    else:
        print(name + '不存在')
    input('输入回车键继续')


def search():
    name = input('输入姓名')
    if name in ab:
        print(name + '的电话号码是:' + ab[name]['phone'])
        print(name + '的微信号码是:%s' % ab[name]['wechat'])
        input('输入回车键继续')
    else:
        print(name + '不存在')
        input('输入回车键继续')


def modify():
    global modifyFlag
    name = input('输入姓名')
    if name in ab:
        print(name + '原电话号码是' + ab[name]['phone'])
        newPhoneNumber = input('请输入电话新号码，输入回车键保留原号码')
        if newPhoneNumber!='':
            while (not phoneCheck(newPhoneNumber)):
                newPhoneNumber = input('请输入正确的电话号码')
            ab[name] ['phone']= newPhoneNumber
            print('电话号码更新成功')

        print(name + '的原微信号码是' + ab[name]['wechat'])
        newWechatNumber = input('输入新的微信号码，输入回车键保留原号码')

        if newWechatNumber!='':
            ab[name] ['wechat']= newWechatNumber
            print('微信号码更新成功')

        modifyFlag=True

    else:
        print(name + '不存在')
    input('输入回车键继续')


def save():
    global modifyFlag
    f = open('ab.data', 'wb')
    p.dump(ab, f)  # dump the object to a file
    modifyFlag=False
    f.close()
    input('保存成功输入回车键继续')


def load():
    global ab
    try:
       f = open('ab.data', 'rb')
       ab=p.load(f) #ab must be use the global,otherwise compiler treat ab as a new local variable
       f.close()
       print('通讯录加载成功')
    except IOError:
        print('初始通讯录为空,但该系统可用')
        input('输入回车键继续')

def phoneCheck(phoneNumber):
    #正则表达式1\d{10}
    phonePattern=r'1\d{10}$'
    if re.match(phonePattern,phoneNumber)==None:
      return False
    else:
      return True

def menu():
    print('通讯录')
    print('0.退出')
    print('1.增加联系人')
    print('2.删除')
    print('3.修改')
    print('4.查找')
    print('5.保存')
    print('6.重新加载')
    print('7.全部联系人')
    print('8.全部删除')

def quit():
    if modifyFlag==True:
        saveFlag=input('如果不保存，请输入"NO"并回车（其它键保存）')
        if saveFlag.upper()!='NO': #default save
            save()
            input('保存成功，输入回车键继续')

def listAll():
    if len(ab)==0:
        print('通讯录为空')
        input('输入回车键继续')
        return
    for name in list(ab.keys()):
        print(name+'的电话号码是:'+ab[name]['phone'])
        print(name+'的微信号码是:'+ab[name]['wechat']+'\n')
    input('输入回车键继续')

def deleteAll():
    if len(ab)==0:
        print('通讯录为空')
        return
    confirm=input("确认删除全部联系人请输入:YES")
    if (confirm=='YES'):
        for name in list(ab.keys()):
            del ab[name]
        input('删除成功，输入回车键继续')
    else:
        input('未删除，输入回车键继续')


def main():
    load()
    while True:
        menu()
        try:
            option = int(input('请选择:'))
            if (option == 1):
                add()
                continue
            elif (option == 2):
                delete()
                continue
            elif (option == 3):
                modify()
                continue
            elif (option == 4):
                search()
                continue
            elif (option ==5):
               save()
               continue
            elif (option == 6):
                load()
                continue
            elif (option == 7):
                listAll()
                continue
            elif (option == 8):
                deleteAll()
                continue
            elif (option == 0):
                quit()
                return
            else:
                print('请输入一个正确的选项(整数)')
                continue
        except ValueError:
            print('请输入一个整数')
            continue


if __name__=='__main__':
   main()
